package entry

import (
	"com.lh.basic.service/lib/middleware"
	"com.lh.basic.service/pb/auth"
	"com.lh.basic.service/pb/menu"
	"com.lh.user.service/pb/user"
	"context"
	"fmt"
	"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
	"google.golang.org/grpc"
	"log"
	"net/http"
	"sync"
)

func InitGateway(opts *user.ServeConfig, wg *sync.WaitGroup) {
	defer wg.Done()
	mux := runtime.NewServeMux(
		runtime.WithMetadata(middleware.SetHeader))
	conn, err := grpc.Dial(
		fmt.Sprintf("%s:%d", opts.Host, opts.Port),
		grpc.WithInsecure(),
	)
	if err != nil {
		log.Fatal(err)
	}

	_ = auth.RegisterAuthServiceHandler(context.Background(), mux, conn)
	_ = menu.RegisterMenuServiceHandler(context.Background(), mux, conn)
	httpServe := &http.Server{
		//Handler: app,
		Handler: middleware.FilterCors(mux, fmt.Sprintf("%s:%d", "localhost", opts.Port+1000)),
		Addr:    fmt.Sprintf("%s:%d", opts.Host, opts.Port+1000),
	}
	log.Printf("start gateway at %s", httpServe.Addr)
	if err := httpServe.ListenAndServe(); err != nil {
		log.Fatal(err)
	}
}
